package com.xgs.web.controller.system;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xgs.common.annotation.Log;
import com.xgs.common.core.controller.BaseController;
import com.xgs.common.core.domain.AjaxResult;
import com.xgs.common.core.domain.entity.SysUser;
import com.xgs.common.core.page.TableDataInfo;
import com.xgs.common.enums.BusinessType;
import com.xgs.common.utils.DateUtils;
import com.xgs.common.utils.uuid.IdUtils;
import com.xgs.system.domain.BasicVersion;
import com.xgs.system.domain.Roster;
import com.xgs.system.domain.RosterHistory;
import com.xgs.system.service.BasicVersionService;
import com.xgs.system.service.RosterHistoryService;
import com.xgs.system.service.RosterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

/**
 * @author JerryLu
 * @date 2024/10/23 11:05
 * @description 名单录入历史数据Controller
 */
@RestController
@RequestMapping("/system/roster_history")
public class RosterHistoryController extends BaseController {
    @Autowired
    private RosterHistoryService historyService;

    @Autowired
    private BasicVersionService versionService;

    @Autowired
    private RosterService rosterService;

    /**
     * 查询名单录入数据列表
     */
    @PreAuthorize("@ss.hasPermi('system:roster_history:list')")
    @GetMapping("/list")
    public TableDataInfo list(RosterHistory history) {
        startPage();
        if (!SysUser.isAdmin(getUserId())) {
            history.setDeptId(getDeptId());
        }
        List<RosterHistory> list = historyService.queryList(history);
        return getDataTable(list);
    }

    /**
     * 获取名单录入数据详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:roster_history:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(historyService.getById(id));
    }

    /**
     * 修改名单录入数据
     */
    @PreAuthorize("@ss.hasPermi('system:roster_history:edit')")
    @Log(title = "名单录入数据", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult edit(@RequestBody RosterHistory history) {
        try {
            String[] arr = history.getExStationId().split(",");
            if (history.getExStationId().contains(",") && arr.length > 0) {
                return AjaxResult.error(-1, "已下发数据禁止添加多个出站口");
            }
            history.setUpdateTime(DateUtils.getNowDate());
            historyService.updateById(history);
            //修改对应数据。添加新的版本号和名单数据
            QueryWrapper<BasicVersion> query = Wrappers.query();
            query.eq("version", history.getVersion());
            BasicVersion vInfo = versionService.getOne(query);

            QueryWrapper<BasicVersion> query1 = Wrappers.query();
            query1.eq("state", 0);
            query1.select("max(version) as version, id");
            query1.groupBy("version", "id");
            BasicVersion info = versionService.getOne(query1);
            String id = "";
            if (info == null) {
                BasicVersion version = new BasicVersion();
                String ver = DateUtils.dateTimeNow();
                version.setId(IdUtils.fastSimpleUUID());
                version.setVersion(ver);
                version.setOperatorId(vInfo.getOperatorId());
                version.setOperatorName(vInfo.getOperatorName());
                version.setDeptId(vInfo.getDeptId());
                version.setCreateTime(DateUtils.getNowDate());
                versionService.save(version);
                id = version.getId();
            } else {
                id = info.getId();
            }

            Roster roster = JSON.parseObject(JSON.toJSONString(history), Roster.class);
            roster.setId(IdUtils.fastSimpleUUID());
            roster.setBasicId(id);
            roster.setSpare3(0);
            roster.setCreateTime(DateUtils.getNowDate());
            rosterService.save(roster);

            return AjaxResult.success("修改成功,已生成新的版本数据");
        } catch (Exception e) {
            e.printStackTrace();
            return error(e.getMessage());
        }
    }

    /**
     * 删除名单录入数据
     */
    @PreAuthorize("@ss.hasPermi('system:roster_history:remove')")
    @Log(title = "名单录入数据", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        boolean msg = false;
        for (String id : ids) {
            RosterHistory his = historyService.getById(id);
            // 状态未删除且下发成功的，删除后生成新的版本号
            if (his.getDelFlag() == 0 && his.getSpare3() == 3) {
                //修改对应数据。添加新的版本号和名单数据
                QueryWrapper<BasicVersion> query = Wrappers.query();
                query.eq("version", his.getVersion());
                BasicVersion vInfo = versionService.getOne(query);

                QueryWrapper<BasicVersion> query1 = Wrappers.query();
                query1.eq("state", 0);
                query1.eq("rownum", 1);
                query1.select("max(version) as version, id");
                query1.groupBy("version", "id");
                BasicVersion info = versionService.getOne(query1);
                String i = "";
                if (info == null) {
                    BasicVersion version = new BasicVersion();
                    String ver = DateUtils.dateTimeNow();
                    version.setId(IdUtils.fastSimpleUUID());
                    version.setVersion(ver);
                    version.setOperatorId(vInfo.getOperatorId());
                    version.setOperatorName(vInfo.getOperatorName());
                    version.setDeptId(vInfo.getDeptId());
                    version.setCreateTime(DateUtils.getNowDate());
                    versionService.save(version);
                    i = version.getId();
                } else {
                    i = info.getId();
                }

                Roster roster = JSON.parseObject(JSON.toJSONString(his), Roster.class);
                roster.setId(IdUtils.fastSimpleUUID());
                roster.setBasicId(i);
                roster.setSpare3(0);
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.DATE, -1); //将日期减去一天,删除就代表不想要此记录
                roster.setEndDate(calendar.getTime());
                roster.setCreateTime(DateUtils.getNowDate());
                rosterService.save(roster);

                msg = true;
            }
            his.setId(id);
            his.setUpdateTime(DateUtils.getNowDate());
            his.setDelFlag(2);
            historyService.updateById(his);
        }
        return msg ? AjaxResult.success("删除成功,已生成新的版本数据") :toAjax(1);
    }

    /**
     * 下发失败强制再下发
     *
     * @param ids
     * @return
     */
    @PostMapping("/forceIssued/{ids}")
    public AjaxResult forceIssued(@PathVariable String[] ids) {
        for (String id : ids) {
            RosterHistory his = historyService.getById(id);

            QueryWrapper<BasicVersion> query = Wrappers.query();
            query.eq("version", his.getVersion());
            BasicVersion vInfo = versionService.getOne(query);

            QueryWrapper<BasicVersion> query1 = Wrappers.query();
            query1.eq("state", 0);
            query1.select("max(version) as version, id");
            query1.groupBy("version", "id");
            BasicVersion info = versionService.getOne(query1);
            String i = "";
            if (info == null) {
                BasicVersion version = new BasicVersion();
                String ver = DateUtils.dateTimeNow();
                version.setId(IdUtils.fastSimpleUUID());
                version.setVersion(ver);
                version.setOperatorId(vInfo.getOperatorId());
                version.setOperatorName(vInfo.getOperatorName());
                version.setDeptId(vInfo.getDeptId());
                version.setCreateTime(DateUtils.getNowDate());
                versionService.save(version);
                i = version.getId();
            } else {
                i = info.getId();
            }

            Roster roster = JSON.parseObject(JSON.toJSONString(his), Roster.class);
            roster.setId(IdUtils.fastSimpleUUID());
            roster.setBasicId(i);
            roster.setSpare3(0);
            roster.setCreateTime(DateUtils.getNowDate());
            rosterService.save(roster);
        }
        return toAjax(1);
    }

    /**
     * 获取车道下发状态
     * 
     * @param stationHex
     * @return
     */
    @GetMapping("/getLaneState/{stationHex}")
    public AjaxResult getLaneState(@PathVariable String stationHex) {
        return toAjax(1);
    }

}
